﻿
using Dt261.db;
using Dt261.Model;
using Dt261.Views;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Panuon.UI.Silver;
using Panuon.UI.Silver.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using DMSkin.Core;
using System.Threading;
using Dt261.jsonmodel;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using Newtonsoft.Json;
using System.Collections;
using LiveCharts;
using LiveCharts.Wpf;
using System.Windows.Media;

//瞬态诱发耳声发射(TEOAE)：耳蜗受到外界短暂脉冲刺激后，经过一定潜伏期，以一定形式释放出的声频能量，其形式由刺激声的特点决定。
//通常使用短声(click)或短音(tone pip)作为刺激声，耳蜗在接受刺激声后20ms内从外耳道内记录声频能量。
//    典型的TEOAE信号为时域显示，瞬态诱发性耳声发射波相对于刺激的延迟时间为2 ~5ms，持续时间为2 ~5ms。
//    TEOAE反应客观、敏感并且速度快。
namespace Dt261.ViewModel
{
    class ResultPageEsVM : GalaSoft.MvvmLight.ViewModelBase
    {

        MemberInfoDb memberDB;
        EroEntityDb eroResultDB;

        private ObservableCollection<EroEntity> allResults;
        private EroEntity selectResult;
        private MemberInfo selectMember;

        private string yijian;

        public MemberInfo SelectMember
        {
            get => selectMember;
            set
            {
               selectMember = value;

                RaisePropertyChanged();

            }
        }
        public ResultPageEsVM()
        {
            memberDB = new MemberInfoDb(dbconfig.DatabasePath);
            eroResultDB = new EroEntityDb(dbconfig.DatabasePath);


            getInitInfo();


            DMSkin.Core.Broadcast.RegisterBroadcast<string>("NavigationBack", (obj) =>
            {
                getInitInfo();
                //getSpeechInfo();
            });


            //
            if (1 == 0)
            {

                EroEntity item = new EroEntity();
                item.Uid = System.Guid.NewGuid().ToString("N");
                item.CreateTime = DateTime.Now;
                item.MemberId = memberDB.GetMembers().First().Uid;
                item.Type = 2;

                for (int j = 0; j < 2; j++)
                {
                    EroResult result = new EroResult();
                    result.Ear = j;
                    result.Intensity = "86dBSPL";
                    result.Ratio = 0.75;
                    result.Energy = 13;
                    result.Uid = System.Guid.NewGuid().ToString("N");

                    Int32[] array = { 0, 841, 1189, 1682, 2378, 3364, 4757 };
                    for (int i = 1; i < 6; i++)
                    {
                        EroFrequency f = new EroFrequency();
                        f.Sort = i;
                        f.Range = array[i] + "-" + array[i + 1];
                        f.Signal = i;
                        f.Noise = i + (new Random().Next()) % 5;
                        f.Resultid = result.Uid;
                        result.frequency.Add(f);
                    }

                    for (int i = 1; i < 6; i++)
                    {
                        EroChart f = new EroChart();
                        f.Time = i;
                        f.Value = (new Random().Next()) % 12 + i;
                        f.Resultid = result.Uid;
                        result.chart.Add(f);
                    }

                    item.results.Add(result);


                }
                eroResultDB.AddEroEntity(item);


            }


        }

        void getInitInfo()
        {
            AllResults = new ObservableCollection<EroEntity>(eroResultDB.GetALLEroEntitysWithName());
            SelectResult = AllResults.FirstOrDefault();
        }


        public ObservableCollection<EroEntity> AllResults { get => allResults; set { Set(ref allResults, value); } }



        public delegate void selectResultchanged();// /*Dictionary<int, TestItem> list*/, bool isright, int mmtype = 0, int needLink = 0);
        //定义一个事件
        public event selectResultchanged SelectResultEvent;

        private EroResult leftResult;
        private EroResult rightResult;

        private ObservableCollection<EroFrequency> leftResultEroFrequency;
        private ObservableCollection<EroFrequency> rightResultEroFrequency;

        private ObservableCollection<EroChart> leftResultEroChart;
        private ObservableCollection<EroChart> rightResultEroChart;

        public ObservableCollection<EroFrequency> LeftResultEroFrequency { get => leftResultEroFrequency; set { leftResultEroFrequency = value; RaisePropertyChanged(); } }
        public ObservableCollection<EroFrequency> RightResultEroFrequency { get => rightResultEroFrequency; set { Set(ref rightResultEroFrequency, value); RaisePropertyChanged(); } }


        public ObservableCollection<EroChart> LeftResultEroChart { get => leftResultEroChart; set { leftResultEroChart = value; RaisePropertyChanged(); } }
        public ObservableCollection<EroChart> RightResultEroChart { get => rightResultEroChart; set { Set(ref rightResultEroChart, value); RaisePropertyChanged(); } }

        public EroEntity SelectResult
        {
            get => selectResult;
            set
            {
                selectResult = value;
            
                // if (SelectResultEvent != null)
                {


                    //SelectPureToneResultEvent(null, true);
                    //SelectPureToneResultEvent(null, false);
                    //SelectPureToneResultEvent(null, true, 1);
                    //SelectPureToneResultEvent(null, false, 1);
                    if (value != null)
                    {
                        Yijian = selectResult.DoctorOption;
                        SelectMember = memberDB.GetOneMemberByUid(selectResult.MemberId);
                        //resultDB.GetChildrenByUid(value);
                        RaisePropertyChanged();
                        //selectPureToneResultIsChange();

                        foreach (EroResult r in selectResult.results)
                        {
                            if (r.Ear == 0)
                            {
                                LeftResult = r;
                                LeftResultEroFrequency = new ObservableCollection<EroFrequency>(r.frequency);
                                LeftResultEroChart = new ObservableCollection<EroChart>(r.chart);
                            }

                            else if (r.Ear == 1)
                            {
                                RightResult = r;
                                RightResultEroFrequency = new ObservableCollection<EroFrequency>(r.frequency);
                                RightResultEroChart = new ObservableCollection<EroChart>(r.chart);
                            }

                        }

                        changechart();
          
                        if (SelectResultEvent != null)
                            SelectResultEvent();

                    }



                }
            }
        }



        //xgwen
        public void changechart()
        {

            if (selectResult.Type == 1)
            {
                YMax = 40;
                YMin = 0;
                //Labels = new[] { "1", "2", "3", "4" };
                var newLabels = new List<string>();
                Formatter = value => (value - 10).ToString("G");
                //zuo
                {
                    List<double> datas = new List<double>();

                    for (int i = 0; i < LeftResult.frequency.Count; i++)
                    {

                        EroFrequency f = LeftResult.frequency[i];
                        datas.Add(f.Signal - f.Noise + 10);
                        newLabels.Add(""+f.Sort);

                    }

                    foreach (var i in datas)
                    {
                        Console.WriteLine(i); // Prints items      
                    }

                    SeriesCollection = null;
                    //左耳的
                    SeriesCollection = new SeriesCollection
                    {
                        new ColumnSeries
                        {
                            Title = "左耳TE",


                            // 2015的条形值
                            // 动态改变数据只需要更改此处的 Values 便可
                            //Values = new ChartValues<double> { 10, 30, 20, 15 }//需要加上10去显示，因有-10
                             Values = new ChartValues<double>(datas)
                        }
                    };
                }

                Labels = newLabels.ToArray();
                //you
                {
                    List<double> datas = new List<double>();

                    for (int i = 0; i < RightResult.frequency.Count; i++)
                    {
                        EroFrequency f = RightResult.frequency[i];
                        datas.Add(f.Signal - f.Noise + 10);
                    }

                    foreach (var i in datas)
                    {
                        Console.WriteLine(i); // Prints items      
                    }
                    //右耳的
                    SeriesCollection2 = null;
                    SeriesCollection2 = new SeriesCollection
                    {
                        new ColumnSeries
                        {
                            Title = "右耳TE",


                            // 2015的条形值
                            // 动态改变数据只需要更改此处的 Values 便可
                            //Values = new ChartValues<double> { 10, 30, 20, 15 }//需要加上10去显示，因有-10
                             Values = new ChartValues<double>(datas)
                        }
                    };
                }

            }
            else
            {
                // X轴的坐标值  Labels = new[] {  "2", "4", "6", "8", "10", "12", "14", "16", "18", "20" };
                Labels = new[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
                // Y轴坐标值
                Formatter = value => value.ToString("G");
                // X轴的坐标值
                //YLabels = new[] { "2", "4", "6", "8", "10", "12", "14", "16", "18" };
                //// Y轴坐标值
                //YFormatter = value => value.ToString("G");
                YMax = 20;
                YMin = -20;
                //zuo
                {

                    List<double> datas = new List<double>();

                    for (int i = 0; i < 20; i++)
                    {
                
                        datas.Add(0);
                    }

                    for (int i = 0; i < LeftResult.chart.Count; i++)
                    {
                        EroChart f = LeftResult.chart[i];
                        datas[f.Time] =  (f.Value);
                    }

                    foreach (var i in datas)
                    {
                        Console.WriteLine(i); // Prints items      
                    }
                    SeriesCollection = null;
                    //右耳的
                    SeriesCollection = new SeriesCollection
                    {
                        // 匿名新建LineSeries对象
                        new LineSeries
                        {
                            // 折线的名称
                            Title = "左耳DP",
                           // Fill = Brushes.Transparent,
                            // 折线的拐点值
                            PointGeometry = DefaultGeometries.None,
                            Values = new ChartValues<double>(datas)
                        },

                    };
                }
                //you
                {
                    List<double> datas = new List<double>();

                    for (int i = 0; i < 20; i++)
                    {

                        datas.Add(0);
                    }
                    for (int i = 0; i < RightResult.chart.Count; i++)
                    {
                        EroChart f = RightResult.chart[i];
                        datas[f.Time] = (f.Value);
                    }
                    SeriesCollection2 = null;
                    //右耳的
                    SeriesCollection2 = new SeriesCollection
                    {
                        // 匿名新建LineSeries对象
                        new LineSeries
                        {
                            // 折线的名称
                            Title = "右耳DP",
                           // Fill = Brushes.Transparent,
                            // 折线的拐点值
                            PointGeometry = DefaultGeometries.None,
                            Values = new ChartValues<double> (datas)
                        },

                    };
                }

         
            }



            ////modifying the series collection will animate and update the chart
            //// 动态添加折线"Series 4"
            //SeriesCollection2.Add(new LineSeries
            //{
            //    Title = "Series 4",
            //    Values = new ChartValues<double> { 5, 3, 2, 4 },
            //    LineSmoothness = 0, //0: straight lines, 1: really smooth lines
            //    PointGeometry = Geometry.Parse("m 25 70.36218 20 -28 -20 22 -8 -6 z"),
            //    PointGeometrySize = 50,
            //    // 折线拐点的表示形状，默认为原点，这里是正方形
            //    PointForeground = Brushes.Gray
            //});

            ////modifying any series values will also animate and update the chart
            //// 动态为折线"Series 4"添加一个值
            //SeriesCollection2[3].Values.Add(5d);

        }


        // 图形数据属性
        public SeriesCollection SeriesCollection { get; set; }
        public SeriesCollection SeriesCollection2 { get; set; }

        //public SeriesCollection SeriesCollection3 { get; set; }

        //public SeriesCollection SeriesCollection4 { get; set; }
        // 标签属性


        public string[] Labels { get => YLabels;  set { YLabels = value;RaisePropertyChanged(); } }
        // Y轴坐标属性
        public Func<double, string> Formatter { get => YFormatter; set { YFormatter = value; RaisePropertyChanged(); } }

        public double YMin { get => Ymin; set { Ymin = value; RaisePropertyChanged(); } }
        public double YMax { get => Ymax; set { Ymax = value; RaisePropertyChanged(); } }

        internal EroResult LeftResult { get => leftResult; set { leftResult = value; RaisePropertyChanged(); } }
        internal EroResult RightResult { get => rightResult; set { rightResult = value; RaisePropertyChanged(); } }

        public string Yijian { get => yijian; set { yijian = value; RaisePropertyChanged(); } }

        private string[] YLabels;
        private Func<double, string> YFormatter;
        private double Ymin;
        private double Ymax;


        //xgwen
    }
}
